<template>
	<view class="topic-page">
		<!-- 搜索栏 -->
		<view class="search-section">
			<view class="search-container">
				<text class="search-icon">🔍</text>
				<input class="search-input" placeholder="搜索话题" v-model="searchKeyword" @input="onSearchInput"
					@confirm="handleSearch" />
				<text class="clear-icon" v-if="searchKeyword" @click="clearSearch">×</text>
			</view>
		</view>

		<!-- Tab栏 -->
		<view class="tab-section">
			<view v-for="tab in tabs" :key="tab.key" class="tab-item" :class="{ active: currentTab === tab.key }"
				@click="switchTab(tab.key)">
				<text class="tab-text">{{ tab.name }}</text>
				<view class="tab-indicator" v-if="currentTab === tab.key"></view>
			</view>
		</view>

		<!-- 话题列表 -->
		<scroll-view class="topic-list" scroll-y="true" :refresher-enabled="true"
			:refresher-triggered="refresherTriggered" @refresherrefresh="onRefresherRefresh"
			@scrolltolower="onReachBottom">
			<view class="topic-container">
				<!-- 搜索结果显示 -->
				<view class="search-result" v-if="searchKeyword && searchResults.length > 0">
					<text class="result-title">搜索结果</text>
					<view v-for="topic in searchResults" :key="topic.id" class="topic-item"
						@click="goToTopicDetail(topic)">
						<view class="topic-main">
							<view class="topic-header">
								<text class="topic-title">#{{ topic.title }}</text>
								<view class="topic-hot" v-if="topic.isHot">
									<text class="hot-icon">🔥</text>
									<text class="hot-text">热点</text>
								</view>
							</view>
							<text class="topic-desc">{{ topic.description }}</text>
							<view class="topic-stats">
								<text class="stat-item">{{ topic.viewCount }} 浏览</text>
								<text class="stat-item">{{ topic.opinionCount }} 观点</text>
								<text class="stat-item">{{ topic.discussionCount }} 讨论</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 正常话题列表 -->
				<view class="topic-list-content" v-else>
					<view v-for="topic in topicList" :key="topic.id" class="topic-item" @click="goToTopicDetail(topic)">
						<view class="topic-main">
							<view class="topic-header">
								<text class="topic-title">#{{ topic.title }}</text>
								<view class="topic-hot" v-if="topic.isHot">
									<text class="hot-icon">🔥</text>
									<text class="hot-text">热点</text>
								</view>
							</view>
							<text class="topic-desc">{{ topic.description }}</text>

							<!-- 观点预览 -->
							<view class="opinions-preview"
								v-if="topic.recentOpinions && topic.recentOpinions.length > 0">
								<view v-for="opinion in topic.recentOpinions" :key="opinion.id" class="opinion-item">
									<image class="user-avatar" :src="opinion.user.avatar" mode="aspectFill"></image>
									<view class="opinion-content">
										<text class="user-name">{{ opinion.user.name }}</text>
										<text class="opinion-text">{{ opinion.content }}</text>
									</view>
								</view>
							</view>

							<view class="topic-footer">
								<view class="topic-stats">
									<text class="stat-item">{{ topic.viewCount }} 浏览</text>
									<text class="stat-item">{{ topic.opinionCount }} 观点</text>
									<text class="stat-item">{{ topic.discussionCount }} 讨论</text>
								</view>
								<text class="update-time">{{ topic.updateTime }}</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 加载状态 -->
				<view class="load-more" v-if="isLoading">
					<text class="load-more-text">加载中...</text>
				</view>
				<view class="no-more" v-if="!hasMore && topicList.length > 0">
					<text class="no-more-text">没有更多话题了</text>
				</view>

				<!-- 空状态 -->
				<view class="empty-state" v-if="!isLoading && topicList.length === 0 && !searchKeyword">
					<text class="empty-icon">💬</text>
					<text class="empty-text">暂无话题</text>
					<text class="empty-desc">快去发表你的观点吧</text>
				</view>

				<!-- 搜索空状态 -->
				<view class="empty-state" v-if="searchKeyword && searchResults.length === 0">
					<text class="empty-icon">🔍</text>
					<text class="empty-text">未找到相关话题</text>
					<text class="empty-desc">换个关键词试试</text>
				</view>
			</view>
		</scroll-view>

		<!-- 创建话题按钮 -->
		<view class="create-topic-btn" @click="goToCreateTopic">
			<text class="create-icon">+</text>
			<text class="create-text">创建话题</text>
		</view>
	</view>
</template>

<script>
	// 模拟云端API
	const mockApi = {
		// 获取话题列表
		getTopicList: (tab, page = 1, pageSize = 10) => {
			return new Promise((resolve) => {
				setTimeout(() => {
					const topics = [];
					const totalItems = 30;
					const startIndex = (page - 1) * pageSize;
					const endIndex = Math.min(startIndex + pageSize, totalItems);

					const tabConfigs = {
						hot: {
							isHot: true,
							baseCount: 1000
						},
						new: {
							isHot: false,
							baseCount: 100
						},
						follow: {
							isHot: false,
							baseCount: 50
						}
					};

					const config = tabConfigs[tab] || tabConfigs.hot;

					for (let i = startIndex; i < endIndex; i++) {
						const topicId = `topic-${tab}-${page}-${i}`;
						const isHot = config.isHot || Math.random() > 0.7;
						const baseCount = config.baseCount;

						const topic = {
							id: topicId,
							title: this.getRandomTopicTitle(i),
							description: this.getRandomTopicDescription(),
							viewCount: Math.floor(Math.random() * baseCount * 10) + baseCount,
							opinionCount: Math.floor(Math.random() * baseCount) + baseCount /
								10,
							discussionCount: Math.floor(Math.random() * baseCount / 2) +
								baseCount / 20,
							isHot: isHot,
							updateTime: this.getRandomTime(),
							category: this.getRandomCategory(),
							recentOpinions: this.getRandomRecentOpinions(topicId)
						};
						topics.push(topic);
					}

					resolve({
						code: 200,
						data: {
							list: topics,
							hasMore: endIndex < totalItems
						}
					});
				}, 800);
			});
		},

		// 搜索话题
		searchTopics: (keyword, page = 1, pageSize = 10) => {
			return new Promise((resolve) => {
				setTimeout(() => {
					// 模拟搜索逻辑
					const allTopics = this.generateSearchData();
					const filteredTopics = allTopics.filter(topic =>
						topic.title.includes(keyword) ||
						topic.description.includes(keyword)
					).slice((page - 1) * pageSize, page * pageSize);

					resolve({
						code: 200,
						data: {
							list: filteredTopics,
							hasMore: filteredTopics.length === pageSize
						}
					});
				}, 500);
			});
		},

		// 工具方法
		getRandomTopicTitle: (index) => {
			const topics = [
				'人工智能未来发展趋势',
				'元宇宙技术应用场景',
				'新能源汽车市场分析',
				'远程办公的利与弊',
				'数字游民生活方式',
				'可持续环保生活',
				'心理健康重要性',
				'区块链技术应用',
				'5G时代的生活改变',
				'虚拟现实娱乐体验',
				'智慧城市建设',
				'生物科技突破',
				'太空探索进展',
				'传统文化保护',
				'教育改革方向'
			];
			return topics[index % topics.length] + ` #${index + 1}`;
		},

		getRandomTopicDescription: () => {
			const descriptions = [
				'探讨这一领域的最新发展和未来趋势，分享你的见解和经验。',
				'这个话题引发了广泛讨论，不同观点激烈碰撞，值得深入思考。',
				'从多个角度分析这一现象，了解背后的原因和影响。',
				'分享你的亲身经历和看法，与其他用户交流互动。',
				'这个话题涉及到我们生活的方方面面，每个人都有自己的看法。'
			];
			return descriptions[Math.floor(Math.random() * descriptions.length)];
		},

		getRandomTime: () => {
			const times = ['刚刚', '1小时前', '3小时前', '今天', '1天前', '2天前', '1周前'];
			return times[Math.floor(Math.random() * times.length)];
		},

		getRandomCategory: () => {
			const categories = ['科技', '生活', '娱乐', '体育', '财经', '教育', '健康'];
			return categories[Math.floor(Math.random() * categories.length)];
		},

		getRandomRecentOpinions: (topicId) => {
			const opinions = [];
			const opinionCount = Math.floor(Math.random() * 3) + 1; // 1-3条观点

			const users = [{
					id: 'user1',
					name: '科技爱好者',
					avatar: '/static/users/user1.png'
				},
				{
					id: 'user2',
					name: '生活达人',
					avatar: '/static/users/user2.png'
				},
				{
					id: 'user3',
					name: '行业专家',
					avatar: '/static/users/user3.png'
				},
				{
					id: 'user4',
					name: '普通用户',
					avatar: '/static/users/user4.png'
				}
			];

			const contents = [
				'我觉得这个方向很有前景，未来会有很大发展空间。',
				'从实际应用来看，还需要解决一些技术难题。',
				'用户体验方面做得不错，但还有改进空间。',
				'这个观点我完全赞同，说出了我的心声。',
				'有不同的看法，我认为应该从另一个角度考虑。',
				'实践出真知，需要更多实际案例来验证。'
			];

			for (let i = 0; i < opinionCount; i++) {
				const user = users[Math.floor(Math.random() * users.length)];
				opinions.push({
					id: `opinion-${topicId}-${i}`,
					content: contents[Math.floor(Math.random() * contents.length)],
					user: user,
					likeCount: Math.floor(Math.random() * 50),
					time: Math.random() > 0.5 ? '刚刚' : '1小时前'
				});
			}

			return opinions;
		},

		generateSearchData: () => {
			const data = [];
			for (let i = 0; i < 20; i++) {
				data.push({
					id: `search-topic-${i}`,
					title: this.getRandomTopicTitle(i),
					description: this.getRandomTopicDescription(),
					viewCount: Math.floor(Math.random() * 10000) + 1000,
					opinionCount: Math.floor(Math.random() * 500) + 50,
					discussionCount: Math.floor(Math.random() * 200) + 20,
					isHot: Math.random() > 0.7,
					updateTime: this.getRandomTime()
				});
			}
			return data;
		}
	};

	export default {
		name: "TopicPage",
		data() {
			return {
				tabs: [{
						key: 'hot',
						name: '热门话题'
					},
					{
						key: 'new',
						name: '最新话题'
					},
					{
						key: 'follow',
						name: '关注话题'
					}
				],
				currentTab: 'hot',
				topicList: [],
				searchResults: [],
				searchKeyword: '',
				isLoading: false,
				hasMore: true,
				currentPage: 1,
				refresherTriggered: false,
				searchTimer: null
			}
		},
		onLoad() {
			this.loadTopics();
		},
		methods: {
			// 切换Tab
			switchTab(tabKey) {
				this.currentTab = tabKey;
				this.currentPage = 1;
				this.topicList = [];
				this.loadTopics(true);
			},

			// 加载话题列表
			async loadTopics(isRefresh = false) {
				if (this.isLoading) return;

				try {
					this.isLoading = true;
					const result = await mockApi.getTopicList(this.currentTab, this.currentPage);

					if (result.code === 200) {
						if (isRefresh || this.currentPage === 1) {
							this.topicList = result.data.list;
						} else {
							this.topicList = [...this.topicList, ...result.data.list];
						}
						this.hasMore = result.data.hasMore;
					}
				} catch (error) {
					console.error('加载话题失败:', error);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				} finally {
					this.isLoading = false;
					this.refresherTriggered = false;
				}
			},

			// 搜索输入处理
			onSearchInput() {
				// 防抖处理
				clearTimeout(this.searchTimer);
				this.searchTimer = setTimeout(() => {
					if (this.searchKeyword.trim()) {
						this.handleSearch();
					} else {
						this.searchResults = [];
					}
				}, 500);
			},

			// 执行搜索
			async handleSearch() {
				if (!this.searchKeyword.trim()) {
					this.searchResults = [];
					return;
				}

				try {
					this.isLoading = true;
					const result = await mockApi.searchTopics(this.searchKeyword.trim());

					if (result.code === 200) {
						this.searchResults = result.data.list;
					}
				} catch (error) {
					console.error('搜索失败:', error);
					uni.showToast({
						title: '搜索失败',
						icon: 'none'
					});
				} finally {
					this.isLoading = false;
				}
			},

			// 清空搜索
			clearSearch() {
				this.searchKeyword = '';
				this.searchResults = [];
			},

			// 跳转到话题详情
			goToTopicDetail(topic) {
				uni.navigateTo({
					url: `/pages/topic-detail/topic-detail?topicId=${topic.id}`
				});
			},

			// 跳转到创建话题
			goToCreateTopic() {
				uni.navigateTo({
					url: '/pages/create-topic/create-topic'
				});
			},

			// 下拉刷新
			onRefresherRefresh() {
				this.refresherTriggered = true;
				this.currentPage = 1;
				if (this.searchKeyword) {
					this.handleSearch();
				} else {
					this.loadTopics(true);
				}
			},

			// 上拉加载更多
			onReachBottom() {
				if (this.isLoading || !this.hasMore) return;

				if (this.searchKeyword) {
					// 搜索结果的加载更多
					this.currentPage++;
					this.handleSearch();
				} else {
					// 正常列表的加载更多
					this.currentPage++;
					this.loadTopics();
				}
			}
		}
	}
</script>

<style scoped>
	.topic-page {
		background: #f5f5f5;
		min-height: 100vh;
	}

	/* 搜索栏样式 */
	.search-section {
		background: white;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
		position: sticky;
		top: 0;
		z-index: 100;
	}

	.search-container {
		display: flex;
		align-items: center;
		background: #f8f9fa;
		border-radius: 30rpx;
		padding: 16rpx 24rpx;
		position: relative;
	}

	.search-icon {
		font-size: 28rpx;
		color: #999;
		margin-right: 16rpx;
	}

	.search-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
	}

	.clear-icon {
		font-size: 36rpx;
		color: #999;
		padding: 8rpx;
	}

	/* Tab栏样式 */
	.tab-section {
		background: white;
		display: flex;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.tab-item {
		flex: 1;
		position: relative;
		padding: 24rpx 0;
		text-align: center;
	}

	.tab-text {
		font-size: 30rpx;
		color: #666;
		font-weight: 500;
		transition: all 0.3s;
	}

	.tab-item.active .tab-text {
		color: #007AFF;
		font-weight: 600;
	}

	.tab-indicator {
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 60rpx;
		height: 4rpx;
		background: #007AFF;
		border-radius: 2rpx;
	}

	/* 话题列表样式 */
	.topic-list {
		height: calc(100vh - 200rpx);
	}

	.topic-container {
		padding: 20rpx;
	}

	.search-result {
		margin-bottom: 20rpx;
	}

	.result-title {
		display: block;
		font-size: 26rpx;
		color: #999;
		margin-bottom: 20rpx;
		padding-left: 10rpx;
	}

	.topic-item {
		background: white;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		transition: all 0.2s;
	}

	.topic-item:active {
		background: #f8f9fa;
		transform: scale(0.99);
	}

	.topic-main {
		display: flex;
		flex-direction: column;
	}

	.topic-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 16rpx;
	}

	.topic-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #007AFF;
		flex: 1;
	}

	.topic-hot {
		display: flex;
		align-items: center;
		background: #fff2f0;
		padding: 8rpx 16rpx;
		border-radius: 20rpx;
	}

	.hot-icon {
		font-size: 24rpx;
		margin-right: 8rpx;
	}

	.hot-text {
		font-size: 22rpx;
		color: #ff4d4f;
		font-weight: 500;
	}

	.topic-desc {
		font-size: 28rpx;
		color: #666;
		line-height: 1.5;
		margin-bottom: 20rpx;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
	}

	/* 观点预览样式 */
	.opinions-preview {
		background: #f8f9fa;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
	}

	.opinion-item {
		display: flex;
		margin-bottom: 16rpx;
	}

	.opinion-item:last-child {
		margin-bottom: 0;
	}

	.user-avatar {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		margin-right: 16rpx;
		flex-shrink: 0;
	}

	.opinion-content {
		flex: 1;
	}

	.user-name {
		font-size: 24rpx;
		color: #007AFF;
		font-weight: 500;
		margin-bottom: 8rpx;
		display: block;
	}

	.opinion-text {
		font-size: 26rpx;
		color: #333;
		line-height: 1.4;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
	}

	/* 话题底部信息 */
	.topic-footer {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.topic-stats {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.stat-item {
		font-size: 24rpx;
		color: #999;
	}

	.update-time {
		font-size: 24rpx;
		color: #999;
	}

	/* 加载状态 */
	.load-more,
	.no-more {
		text-align: center;
		padding: 40rpx;
		color: #6c757d;
		font-size: 26rpx;
	}

	/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 120rpx 40rpx;
		text-align: center;
	}

	.empty-icon {
		font-size: 120rpx;
		margin-bottom: 30rpx;
		opacity: 0.5;
	}

	.empty-text {
		font-size: 32rpx;
		color: #666;
		margin-bottom: 16rpx;
	}

	.empty-desc {
		font-size: 26rpx;
		color: #999;
	}

	/* 创建话题按钮 */
	.create-topic-btn {
		position: fixed;
		bottom: 40rpx;
		right: 40rpx;
		background: linear-gradient(135deg, #007AFF, #00C6FF);
		color: white;
		padding: 20rpx 30rpx;
		border-radius: 50rpx;
		display: flex;
		align-items: center;
		box-shadow: 0 8rpx 25rpx rgba(0, 122, 255, 0.3);
		z-index: 100;
	}

	.create-icon {
		font-size: 32rpx;
		margin-right: 8rpx;
		font-weight: bold;
	}

	.create-text {
		font-size: 26rpx;
		font-weight: 500;
	}

	/* 响应式设计 */
	@media (max-width: 768rpx) {
		.search-section {
			padding: 16rpx 24rpx;
		}

		.topic-item {
			padding: 24rpx;
		}

		.topic-title {
			font-size: 30rpx;
		}

		.topic-desc {
			font-size: 26rpx;
		}

		.create-topic-btn {
			bottom: 30rpx;
			right: 30rpx;
			padding: 18rpx 24rpx;
		}
	}
</style>